package com.zelin.model.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * TCP通信:
 * 客户端
 */
public class client {
    public static void main(String[] args) {
        Socket socket =null;
        OutputStream outputStream =null;
        InputStream inputStream =null;

        //创建客户端对象,指定连接的主机IP和端口
        try {
            socket = new Socket("192.168.5.1", 6666);
            System.out.println("客户端已经创建");

            //获得字节数出流对象
            outputStream = socket.getOutputStream();
            String str="hello,world....你好客服务端!";

            //写入数据到字节输出流
            outputStream.write(str.getBytes());
            System.out.println("数据已发送!");

            //从服务端接受数据
            inputStream = socket.getInputStream();
            byte[] b=new byte[1024];
            int length = inputStream.read(b);
            String string=new String(b);
            System.out.println("服务端:"+string);


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                assert inputStream != null;
                inputStream.close();
                outputStream.flush();
                outputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
